import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import { Drawer, Card, Row, Col, List, Select, Tooltip, Icon, Input, Button, Form, Modal } from 'antd';
import { getSubmitParcels, getDeleteParcelId } from '../../module/action';
//------------------------------------------------
import DrawerStep3 from './DrawerStep3'
import DetailDawer from './DetailDrawer'
import Footers from '../Footers'
//------------------------------------------------
import './tosend.scss'

const Option = Select.Option;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

class DrawerStep2 extends Component {
  state = {
    detailVisible: false,
    step_3_Visible: false,
    courier: { expressLogo: "http://image-dvlp.oss-cn-hangzhou.aliyuncs.com/logistic/express_yto.jpg", expressName: "圆通快递", expressCode: "YTO" },
    expressType: 2,
    detailSource: {},
    waybillNoList: [],
  }

  componentWillReceiveProps(nextProps) {//父级props变化石调用
    const { submitParcels } = nextProps
    if (submitParcels.length > 0) {
      this.setState({
        step_3_Visible: true
      })
    }
  }

  detailHanlder = (data) => {
    this.setState({
      detailVisible: true,
      detailSource: data
    });
  }
  deleteHanlder = (data, key) => {
    const { sendTypeList } = this.props
    const newSendTypeList = []
    sendTypeList && sendTypeList.map((item, index) => {
      if (key !== index) {
        newSendTypeList.push(item)
      }
    })
    if (newSendTypeList.length === 0) {
      Modal.confirm({
        title: '系统提示',
        content: '当前是最后一个包裹，确定要删除吗？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          this.props.getDeleteParcelId(newSendTypeList)
          this.props.onClose()
        },
        onCancel: () => { }
      });
    } else {
      this.props.getDeleteParcelId(newSendTypeList)
    }
  }

  onCloseDetailDrawer = () => {
    this.setState({
      detailVisible: false,
    });
  }

  drawerStep_3 = () => {
    const { courier } = this.state
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!values || err) return
      const { sendTypeList } = this.props
      const parcelList = []
      sendTypeList.map((item, index) => {
        const goodsKey = []
        item.goodsItemInfo.map(colItem => {
          goodsKey.push(colItem.id)
        })
        parcelList.push({
          expressCode: courier.expressCode,
          expressLogo: courier.expressLogo,
          expressName: courier.expressName,
          expressType: 2,
          goodsKey: goodsKey,
          waybillNo: values[`number_${index + 1}`]
        })
      })
      this.props.getSubmitParcels({ submitParcelInfo: parcelList })
      // this.setState({
      //   step_3_Visible: true
      // })
    })
  }
  onCloseDrawerStep_3 = () => {
    window.location.reload()
  }

  onSelectCompany = (value, option) => {
    this.setState({
      courier: {
        expressCode: value,
        expressLogo: option.props['data-img'],
        expressName: option.props['data-name']
      },
    });
  }

  vilidNumber = (rule, value, callback) => {
    if (!value) { callback(); return }
    const { waybillNoList } = this.state
    const { sendTypeList } = this.props
    for (let i = 1; i <= sendTypeList.length; i++) {
      const newArray = waybillNoList.slice();
      newArray[i] = value;
      if (rule.field === `number_${i}`) {
        for (let j = 1; j < newArray.length; j++) {
          // console.log(`newArray:`, newArray, i, j)
          if (j === i) continue //跳过当前的迭代。
          if (value === newArray[j]) {
            callback('运单号相同啦！')
          }
        }
        this.setState({ waybillNoList: newArray })
      }
    }
    callback()
  }

  inputOnBlur = (e) => {
    let value = e.target.value
    console.log(`请求：效验运单号接口（无接口）=====>`, value)
  }

  render() {
    const { detailVisible, courier, detailSource, step_3_Visible } = this.state
    const { visible, dataSource, onClose, express, sendTypeList } = this.props;
    const { getFieldDecorator } = this.props.form;
    const btmRight = <React.Fragment><Button onClick={this.drawerStep_3} type="primary">提交</Button></React.Fragment>
    // console.log(sessionDeleteList)

    return (
      <Drawer
        className="drawer-step"
        placement="right"
        width={'100%'}
        closable={false}
        onClose={onClose}
        visible={visible}
      >
        <Card className="drawer-top">
          <Row type="flex" justify="space-between">
            <Col span={20}>
              <Row type="flex" justify="start">
                <Col>当前进度：</Col>
                <Col><div>
                  <span className="radius radius-color"></span>
                  <span className="current-span">选择寄件方式</span>
                  <span className="divider-line"></span>
                  <span className="radius"></span>
                  <span>提交成功</span>
                </div></Col>

              </Row>
            </Col>
            <Col className="text-right color-primary" span={4}><span className="span-back" onClick={onClose}>返回</span></Col>
          </Row>
        </Card>
        <List>
          <List.Item>
            <Col span={12}>
              <label>选择寄送方式：</label>
              <Select defaultValue="self" style={{ width: 150 }} disabled>
                <Option value="self">自己联系物流</Option>
              </Select>
            </Col>
            <Col span={12}>
              <label>选择快递公司：</label>
              <Select defaultValue={courier.expressCode} style={{ width: 150 }} onChange={this.onSelectCompany} >
                {express && express.map(item => <Option key={item.expressCode} data-img={item.expressLogo} data-name={item.expressName}>
                  <div className="courier-img"><img src={item.expressLogo} /></div>{item.expressName}
                </Option>)}
              </Select>
            </Col>
          </List.Item>
        </List>
        {sendTypeList && sendTypeList.map((item, index) => {
          return (
            <List key={index}>
              <List.Item>
                <Row className="list-row" type="flex" justify="space-between">
                  <Col span={20}>
                    <span className="list-radius"></span>包裹{index + 1}
                  </Col>
                  <Col><Tooltip title="取消本次寄送"><Icon onClick={() => this.deleteHanlder(item, index)} className="color-primary" type="delete" /></Tooltip></Col>
                </Row>
              </List.Item>
              <List.Item>
                <Row className="list-row" type="flex" justify="space-between">
                  <Col className="list-btm" span={22}>
                    <Row>
                      <Col span={12}>
                        <span>批次封面：<span className="color-primary">{item.goodsCountInfo.coverCount}</span>个</span>
                        <span>发票联：<span className="color-primary">{item.goodsCountInfo.invoiceSheet1Count}</span>张</span>
                        <span>抵扣联：<span className="color-primary">{item.goodsCountInfo.invoiceSheet2Count}</span>张</span>
                        <span>附件：<span className="color-primary">{item.goodsCountInfo.attachmentCount}</span>个</span>
                        <span>销货清单：<span className="color-primary">{item.goodsCountInfo.salesBillCount}</span>个</span></Col>
                      <Col span={6}>
                        <div className="courier-img"><img src={courier.expressLogo} /></div>
                        <span>{courier.expressName}</span>
                      </Col>
                      <Col span={6}>
                        {/* <label>运单号：</label><Input placeholder="请输入快递单号" style={{ width: '200px' }} /> */}
                        <Form.Item className="step2-formitem" {...formItemLayout} label="运单号">
                          {getFieldDecorator(`number_${index + 1}`, {
                            rules: [{ required: true, message: '运单号不能为空!' }, {
                              validator: this.vilidNumber
                            }],
                          })(<Input onBlur={this.inputOnBlur} style={{ width: 200 }} placeholder="请输入运单号" />)}
                        </Form.Item>
                      </Col>
                    </Row>
                  </Col>
                  <Col><Tooltip title="查看包裹详情"><Icon onClick={() => this.detailHanlder(item)} className="color-primary" type="copy" /></Tooltip></Col>
                </Row>
              </List.Item>
            </List>
          )
        })}

        <Footers btmLeft={""} btmRight={btmRight} />
        {detailVisible &&
          <DetailDawer
            visible={detailVisible}
            dataSource={detailSource}
            onClose={this.onCloseDetailDrawer} />
        }
        {step_3_Visible &&
          <DrawerStep3
            visible={step_3_Visible}
            // dataSource="666"
            onClose={this.onCloseDrawerStep_3} />
        }
      </Drawer>
    );
  }
}


function mapStateToProps(state) {
  const { express, sendTypeList, submitParcels } = state.logistics;
  return {
    express,//物流
    sendTypeList,//包裹详情
    submitParcels
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    getSubmitParcels,//提交包裹
    getDeleteParcelId,//删除包裹
  }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Form.create()(DrawerStep2));
